package com.hhhn.wk.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.login.perfect.PerfectActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.AppValidationMgr;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.ControlKeyboardLayout;
import com.hhhn.wk.utils.MD5Util;
import com.hhhn.wk.utils.mi.AES;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/2/22 0022    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 注册
 * * * * * * * * * * * */
public class RegisterActivity extends BaseActivity {
    private LinearLayout activity_login;//布局
    private EditText et_phone;//手机号
    private EditText et_code;//验证码
    private TextView tv_getCode;//获取验证码
    private EditText et_pwd;//密码
//    private EditText et_name;//店面名称
//    private EditText et_address;//店面地址
    private LinearLayout ll_login;//注册
    private TextView tv_agreement;//协议
    private ImageView iv_visual;//可视密码  m默认 不可见
    private boolean visual=true;
    private Context context;
    private BaseActivity activity;
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_register);
        context=RegisterActivity.this;
        activity=this;
    }

    @Override
    protected void initView() {
        iv_visual=findViewById(R.id.iv_visual);
        activity_login=findViewById(R.id.activity_login);
        et_phone=findViewById(R.id.et_phone);
        et_code=findViewById(R.id.et_code);
        tv_getCode=findViewById(R.id.tv_getCode);
        et_pwd=findViewById(R.id.et_pwd);
//        et_name=findViewById(R.id.et_name);
//        et_address=findViewById(R.id.et_address);
        ll_login=findViewById(R.id.ll_login);
        tv_agreement=findViewById(R.id.tv_agreement);
//        ControlKeyboardLayout.controlKeyboardLayout(activity_login,ll_login);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initClick() {
            tv_agreement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    startActivity(new Intent(context,AgreementActivity.class));

                    AllPublic.linkH5(activity, activity,"用户协议", Constants.userAgreement);


                }
            });
        iv_visual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (visual){
                    iv_visual.setImageResource(R.mipmap.ic_yanjing_p);
                    et_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    visual=false;
                }else {
                    iv_visual.setImageResource(R.mipmap.ic_yanjing_n);
                    et_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    visual=true;
                }
            }
        });
        ll_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                judge();
            }
        });
        tv_getCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCode();
            }
        });
    }
    //判断
    private void  judge(){
        String str_phone = et_phone.getText().toString().trim();
        String str_pwd = et_pwd.getText().toString().trim();
        String str_code = et_code.getText().toString().trim();
//        String str_name = et_name.getText().toString().trim();
//        String str_address = et_address.getText().toString().trim();
        if (str_phone==null||"".equals(str_phone)){
            toastWk("请输入手机号");
            return;
        }
        if (str_code==null||"".equals(str_code)){
            toastWk("验证码不能为空");
            return;
        }
        if (str_pwd==null||"".equals(str_pwd)){
            toastWk("密码不能为空");
            return;
        }
        if (!AppValidationMgr.isPhone(str_phone)){
            toastWk("手机号输入有误，请重新输入");
            return;
        }
//        if (str_name==null||"".equals(str_name)){
//            toastWk("请输入店铺名称");
//            return;
//        }
//        if (str_address==null||"".equals(str_address)){
//            toastWk("请输入店铺地址");
//            return;
//        }
        /**
         * 吊起后台接口
         */
        getRegister();
    }

    //获取验证码
    public void getCode() {
        String str_phone = et_phone.getText().toString().trim();
        if (str_phone==null||"".equals(str_phone)){
            toastWk("请输入手机号");
            return;
        }
        if (!AppValidationMgr.isPhone(str_phone)){
            toastWk("手机号输入有误，请重新输入");
            return;
        }
        showLoad();
        RequestParams params = AllPublic.getParamsValid(activity, "/getValidate", false);


        try {
            JSONObject person=new JSONObject();
            person.put("phone",et_phone.getText().toString().trim());/*手机号*/
            person.put("doType",1);/*验证码*/
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                         toastWk("获取成功");
                        final MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000, 1000);
                        myCountDownTimer.start();
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("获取验证码-第二个", ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("获取验证码-第三个", cex + "");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                Log.d("获取验证码-第四个", "onFinished");
                dismissLoad();
            }
        });
    }

    //复写倒计时
    private class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            tv_getCode.setClickable(false);
            tv_getCode.setText(l/1000+"s");
        }
        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            tv_getCode.setText("重新获取");
            //设置可点击
            tv_getCode.setClickable(true);
        }
    }
    //注册
    public void getRegister() {
        showLoad();
        RequestParams params = AllPublic.getParamsAccount(activity, "/register", false);
        try {
            JSONObject person=new JSONObject();
            person.put("phone",et_phone.getText().toString());
            person.put("code",et_code.getText().toString());
            person.put("password",MD5Util.md5(et_pwd.getText().toString().trim()));
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        String id = jsonObject.getString("data");
                        toastWk("注册成功");
                        Intent intent=new Intent(context,PerfectActivity.class);
                        intent.putExtra("userId",id);
                        startActivity(intent);
                        finish();
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogWk("注册成功-第二个："+ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                LogWk("注册成功-第三个：");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                LogWk("注册成功-第四个：");
                dismissLoad();
            }
        });
    }
}
